package com.googlecode.i78ba.forum;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.googlecode.i78ba.login.User;

@Controller
@RequestMapping(value = "/forum")
public class ForumController {
	private static Logger log = LoggerFactory.getLogger(ForumController.class);
	
	@Autowired
	private ForumService forumService;
	
	@RequestMapping(value = "")
	public String forum(Model model){
		forumService.forum(model);
		return "forum";
	}
	
	@RequestMapping(value = "topic")
	public String topic(HttpServletRequest request, Model model) {
		String topicIdS = request.getParameter("id");
		String pageS = request.getParameter("page");
		forumService.topic(topicIdS,pageS,model);
		return "topic";
	}
	
	@RequestMapping(value = "post")
	public String post(HttpServletRequest request, Model model) {
		String postIdS = request.getParameter("id");
		String pageS = request.getParameter("page");
		String uidS = request.getParameter("uid");
		forumService.post(postIdS,pageS,uidS, model);
		return "post";
	}
	
	@RequestMapping(value = "postNewFast")
	@ResponseBody
	public Map<String, Object> postNewFast(HttpServletRequest request,Model model){
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			String postTitle = request.getParameter("post_title");
			log.debug("postTitle -> " + postTitle);
			String postContent = request.getParameter("post_content");
			log.debug("postContent -> " + postContent);
			String topicId = request.getParameter("topic_id");
			
			User user = (User)request.getSession().getAttribute("user");
			
			forumService.postNewFast(postTitle,postContent,topicId,user,data);
			data.put("state", "success");
		} catch (Exception e) {
			data.put("state", "fail");
			log.error("",e);
		}
		return data;
	}
	
	@RequestMapping(value = "replyNew")
	@ResponseBody
	public Map<String, Object> replyNew(HttpServletRequest request,Model model){
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			User user = (User)request.getSession().getAttribute("user");
			String replyContent = request.getParameter("replyContent");
			String replyPostId = request.getParameter("replyPostId");
			forumService.replyNew(replyContent,replyPostId,user);
			data.put("state", "success");
		} catch (Exception e) {
			data.put("state", "fail");
			log.error("",e);
		}
		return data;
	}
}
